using System;
using System.IO;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;

namespace JMClient.Tools;

/// <summary>
/// JSON 工具类 - 基于 Newtonsoft.Json
/// </summary>
public static class JsonHelper
{
    /// <summary>
    /// 默认的 JSON 设置
    /// </summary>
    private static readonly JsonSerializerSettings DefaultSettings = new()
    {
        Formatting = Formatting.Indented,
        NullValueHandling = NullValueHandling.Ignore,
        DefaultValueHandling = DefaultValueHandling.Include,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };

    /// <summary>
    /// 从文件读取 JSON 并反序列化为对象
    /// </summary>
    /// <typeparam name="T">目标类型</typeparam>
    /// <param name="filePath">文件路径</param>
    /// <param name="logger">日志记录器（可选）</param>
    /// <returns>反序列化的对象，失败时返回默认值</returns>
    public static T? LoadFromFile<T>(string filePath, ILogger? logger = null)
    {
        try
        {
            if (!File.Exists(filePath))
            {
                logger?.LogWarning("文件不存在: {FilePath}", filePath);
                return default;
            }

            var json = File.ReadAllText(filePath);
            var result = JsonConvert.DeserializeObject<T>(json, DefaultSettings);
            logger?.LogInformation("成功从文件加载 JSON: {FilePath}", filePath);
            return result;
        }
        catch (Exception ex)
        {
            logger?.LogError(ex, "从文件加载 JSON 失败: {FilePath}", filePath);
            return default;
        }
    }

    /// <summary>
    /// 将对象序列化为 JSON 并保存到文件
    /// </summary>
    /// <param name="obj">要保存的对象</param>
    /// <param name="filePath">文件路径</param>
    /// <param name="logger">日志记录器（可选）</param>
    /// <returns>是否保存成功</returns>
    public static bool SaveToFile(object obj, string filePath, ILogger? logger = null)
    {
        try
        {
            // 确保目录存在
            var directory = Path.GetDirectoryName(filePath);
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            var json = JsonConvert.SerializeObject(obj, DefaultSettings);
            File.WriteAllText(filePath, json);
            logger?.LogInformation("成功保存 JSON 到文件: {FilePath}", filePath);
            return true;
        }
        catch (Exception ex)
        {
            logger?.LogError(ex, "保存 JSON 到文件失败: {FilePath}", filePath);
            return false;
        }
    }

    /// <summary>
    /// 验证 JSON 字符串格式
    /// </summary>
    /// <param name="json">要验证的 JSON 字符串</param>
    /// <returns>是否有效</returns>
    public static bool IsValidJson(string json)
    {
        try
        {
            JsonConvert.DeserializeObject(json);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 深度克隆对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="obj">要克隆的对象</param>
    /// <returns>克隆的对象</returns>
    public static T? DeepClone<T>(T obj)
    {
        if (obj == null) return default;
        
        try
        {
            var json = JsonConvert.SerializeObject(obj, DefaultSettings);
            return JsonConvert.DeserializeObject<T>(json, DefaultSettings);
        }
        catch
        {
            return default;
        }
    }
} 